package com.dmall.graph.dfs.app;

import com.dmall.graph.Graph;

import java.util.ArrayList;

public class CCImprove {

    private Graph G;
    private final int[] visited;
    private int cccount = 0;

    public CCImprove(Graph G) {
        this.G = G;
        this.visited = new int[G.V()];
        for (int i = 0; i < this.visited.length; i++) {
            this.visited[i] = -1;
        }

        for (int i = 0; i < G.V(); i++) {
            if (visited[i] == -1) {
                dfs(i, cccount);
                cccount ++;
            }
        }
    }

    private void dfs(int v, int ccid) {
        visited[v] = ccid;
        for (Integer w : G.adj(v)) {
            if (visited[w] == -1) {
                dfs(w, ccid);
            }
        }
    }

    public int count() {
        return cccount;
    }

    public boolean isCollected(int v, int w) {
        G.validateVertex(v);
        G.validateVertex(w);
        return visited[v] == visited[w];
    }

    public ArrayList<Integer>[] components() {
        ArrayList<Integer>[] components = new ArrayList[cccount];
        for (int i = 0; i < cccount; i++) {
            components[i] = new ArrayList<>();
        }
        for (int i = 0; i < G.V(); i++) {
            components[visited[i]].add(i);
        }
        return components;
    }

    public static void main(String[] args) {
        String filePath = CCImprove.class.getClassLoader().getResource("g.txt").getPath();
        Graph graph = new Graph(filePath);
        CCImprove cc = new CCImprove(graph);
        System.out.println(cc.count());
        System.out.println(cc.isCollected(0, 6));
        System.out.println(cc.isCollected(0, 5));
        ArrayList<Integer>[] components = cc.components();
        for (ArrayList<Integer> component : components) {
            for (Integer v : component) {
                System.out.print(v + " ");
            }
            System.out.println();
        }
    }
}
